/**
 *@Description 订单首页
 *@Author zhangnf
 *@Date 2015-09-23
 */
var orderCtrl  = new XFApp.client();
XFApp.client.prototype.order = {
	successCode : "10000",
	page : null,
	importView : null,
	pageData : null,
	urlItems : {
		queryByPageURL : basePath+"/userCenter/order/getPage",
		delOrderURL : basePath+"/userCenter/order/delOrder",
		submitOrderURL : basePath+"/userCenter/order/submitOrder",
		uploadBatchURL : basePath+"/userCenter/order/uploadBatch",
		payOrderURL	: basePath+"/userCenter/order/payOrder",
		addressModifyURL : basePath+"/userCenter/order/addressModify"
	},
	queryPage : function(){
		_this = this;
		if(!!_this.page){
			_this.page.page("remote",0,$('#searchForm').serialize());
		}else{
		_this.page = $("#page").page({
			pageSize : 10,
			currentPageIndex : Number($("#currentPageIndex").val())-1,
			remote: {
				url: _this.urlItems.queryByPageURL,
		        params: $('#searchForm').serialize(), 
		        success: function (data, pageIndex) {
		        	$("#currentPageIndex").val(data.result.pageNo);
		        	if(data.code==_this.successCode){
		        		var pageResult = data.result;
		        		if(null == data 
								|| null == data.result 
									|| null == data.result.itemList
										|| data.result.itemList.length < 1){
		        			$("#page_grid").html('<div style="text-align:center;background-color: #ebebeb;">暂无数据</div>');
		        		}else{
		        			for(var index in pageResult.itemList){
		        				var element = pageResult.itemList[index];
		        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
		        			}
		        			_this.renderTable(pageResult.itemList);
		        		}
		        	}else{
		        		window.webDialogUtil.alert("提示","操作失败");
		        	}
		        },
		        error : function(){
		        	window.webDialogUtil.alert("提示","操作失败");
		        }
			},
			firstBtnText : '首页',
			lastBtnText : '尾页',
			prevBtnText : '上一页',
			nextBtnText : '下一页',
			showInfo : true,
			showJump : true,
			jumpBtnText : '跳转',
			showPageSizes : true,
			infoFormat : '共{pageCount}页,{total}项'
		});
		}
	},
	renderTable : function(data){
		var _html = '';
		this.pageData = data;
		for(i = 0 ; i < data.length ; i++){
			var _htmlDetails = '';
			var dockStatus = true;
			var detailIndex = 0;
			for(j = 0 ; j < data[i].orderDetailLst.length ; j++){
				if(detailIndex > 1) break;
				var _dockStatus = true;
				detailIndex = j;
				if("40" != data[i].orderDetailLst[j].dockStatus){
					_dockStatus = false;
					dockStatus = false;
				}
				_htmlDetails +=''
					+'             <li '+(_dockStatus?'':'style="color:red;"')+'> '
					+'             <span class="dib" style="width: 40px;">&nbsp;</span> '
					+'             <span class="dib" style="width: 100px;">'+ this.getStr(data[i].orderDetailLst[j].sku)+'</span> '
					+'             <span class="dib" style="width: 260px;">'+ this.getStr(data[i].orderDetailLst[j].itemName)+'</span> '
					+'             <span class="dib" style="width: 90px;">'+ data[i].orderDetailLst[j].price+'</span> '
					+'             <span class="dib" style="width: 60px;">'+ data[i].orderDetailLst[j].qty+'</span> '
					+'             <span class="dib" style="width: 60px;">'+ data[i].orderDetailLst[j].currency+'</span> '
					+'             </li> ';
			}
			_html +=
				'<div class="mt20 tb-box">'
				+' <div class="tb-tit"> '
				+' 	<a class="zi-icon zi-up fr ml20" href="javascript:;" onclick="orderCtrl.order.openCloseRow('+i+')">收缩</a> '
				+' 	<input id="orderRowStatus'+i+'" type="hidden" value="0"/>'
				+	(20==data[i].orderStatus ?'<a class="zi-icon zi-del fr" href="javascript:;" onclick="orderCtrl.order.delView('+data[i].orderNo+','+data[i].id+')">删除</a> ':'')
				+	(20==data[i].orderStatus || 30==data[i].orderStatus || 29==data[i].orderStatus?'<a class="zi-icon zi-edit fr" href="'+basePath+'/userCenter/order/detail?id='+data[i].id+'">编辑</a> ':'')
				+'	<a class="zi-icon zi-search fr" href="'+basePath+'/userCenter/order/view?id='+data[i].id+'">查看</a> '
				+' 	<span class="wib"><input name="chk_list" type="checkbox" '+((20==data[i].orderStatus || 30==data[i].orderStatus) && dockStatus?'':'disabled="true"')+' value="'+data[i].id+'"/></span> '
				+' 	<span>订单号：'+data[i].orderNo+'</span> '
				+' 	<span class="ml20 c666">销售订单号：'+data[i].saleOrderNo+'</span> '
				+' 	<strong class="ml50 orange">状态：'+dksCtrl.dockerstatus.get(data[i].orderStatus)+'</strong> '
				+	((20==data[i].orderStatus || 30==data[i].orderStatus || 29==data[i].orderStatus)&&dockStatus?'<span><a href="javascript:;" class="btn_auto_25 btn_gray w_100 ml20" onclick="orderCtrl.order.doSubmitOrder('+data[i].id+')">提交订单</a></span>':'')
				+	(dockStatus?'':'<span style="color:red;margin-left:10px;">订单中包含未备案商品,请查看商品申报状态</span>')
				+' </div> '
				+' <div id="orderRowDiv'+i+'" class="tb-bd clearfix" style="display:none;"> '
				+' 		<ul id="detailUL'+i+'" class="tb-bd-list"> '
				+			_htmlDetails
				+' 		</ul> '
				+' 		<ul class="tb-bd-item"> '
				+'             <li>运单号</li> '
				+'             <li>'+data[i].trackingNumber+'</li> '
				+'             <li>包裹重量（kg）</li> '
				+'             <li>运费（￥）</li> '
				+'             <li>'+data[i].freight+'</li> '
				+'             <li>'+data[i].pkgWeight+'</li> '
				+'             <li>报关报检（￥）</li> '
				+'             <li>-</li> '
				+'             <li>总费用（￥）</li> '
				+'             <li>申报总价值（USD）</li> '
				+'             <li>'+data[i].goodsValue+'</li> '
				+				(0==data[i].payStatus?'<li class="red">'+data[i].freight+' <a class="ml10 btn_auto_20 btn_blue w_100" style="width: 60px;" onclick="orderCtrl.order.payOrder('+data[i].id+','+data[i].orderNo+')" href="javascript:;">支付</a></li> ':'')
				+				(1==data[i].payStatus?'<li class="red">'+data[i].freight+' <span class="ml20">已支付</span></li> ':'')
				+'             <li><span onclick="orderCtrl.order.tracking('+i+')" style="cursor:pointer">物流轨迹</span></li> '
				+'             <li>收货地址&nbsp;'
				+			   ((20==data[i].orderStatus || 29==data[i].orderStatus)?'<span onclick="orderCtrl.order.addModify('+i+')" style="cursor:pointer">修改</span>':'<span onclick="orderCtrl.order.addView('+i+')" style="cursor:pointer">查看</span>')
				+'			   </li> '
				+'             <li>&nbsp;</li> '
				+'         </ul> '
				+'     <div class="tb-more" onclick="orderCtrl.order.showModeDetails('+i+')">显示更多</div> '
				+'	   <input id="detailModeId'+i+'" type="hidden" value="'+detailIndex+'"/>'
				+' </div> '
				+'  <div id="address'+i+'" class="z-item mt20" style="display:none"> '
				+'     <p class="c666"><strong>收货信息</strong></p> '
				+'     <div class="z-item mt10"> '
				+'         <label for="" class="z-label tar">收货人：</label> '
				+'         <span>'+data[i].consignee+'</span> '
				+'         <label for="" class="z-label tar ml50">联系电话：</label> '
				+'         <span>'+data[i].consigneeTel+'</span> '
				+'     </div> '
				+'     <div class="z-item"> '
				+'         <label for="" class="z-label tar">国家/地区：</label> '
				+'         <span>'+data[i].consigneeNation+'</span> '
				+'     </div> '
				+'     <div class="z-item"> '
				+'         <label for="" class="z-label tar">收货地址：</label> '
				+'         <span>'+data[i].consigneeAdd+'</span> '
				+'     </div> '
				+'  </div> '
				+'  <div id="addressModyfy'+i+'" class="z-item mt20 vt-line" style="display:none"> <form id="addressForm'+i+'"> '
				+'      <p class="c666"><strong>收货信息</strong></p> '
				+'      <div class="z-item mt10"> '
				+'			<input name="id" type="hidden" value="'+data[i].id+'"/> '
				+'          <label for="" class="z-label tar">收货人：</label> '
				+'          <input id="consignee" name="consignee" type="text" value="'+data[i].consignee+'" class="z-input"/> '
				+'          <label for="" class="z-label tar m100">联系电话：</label> '
				+'          <input id="consigneeTel" name="consigneeTel" type="text" value="'+data[i].consigneeTel+'" class="z-input"/> '
				+'          <label for="" class="z-label tar ml00">邮政编码 ：</label> '
				+'          <input id="consigneePost" name="consigneePost" type="text" value="'+data[i].consigneePost+'" class="z-input"/> '
				+'      </div> '
				+'      <div class="z-item"> '
				+'          <label for="" class="z-label tar">国家/地区：</label> '
				+'          <div class="input-group"> '
				+'              <input id="nation'+i+'" name="nationValidate" type="text" class="z-input" autocomplete="off" maxlength="20"/> '
				+'              <input id="nationHidden'+i+'" name="consigneeNation" value="'+data[i].consigneeNation+'" type="text" style="display: none;"> '
				+'              <div class="input-group-btn"> '
				+'                  <button type="button" class="input-group-link" data-toggle="dropdown"> '
				+'                      <span class="caret"></span> '
				+'                  </button> '
				+'                  <ul class="dropdown-menu" role="menu"></ul> '
				+'               </div> '
				+'          </div> '
				+'          <label for="" class="z-label tar">城市：</label> '
				+'          <input id="consigneeCity" name="consigneeCity" type="text" class="z-input"/> '
				+'      </div> '
				+'      <div class="z-item"> '
				+'          <label for="" class="z-label tar">收货地址：</label> '
				+'          <input id="consigneeAdd" name="consigneeAdd" type="text" value="'+data[i].consigneeAdd+'" class="z-input"/> '
				+'      </div> '
				+'  </form></div> '
				+'</div> '
		}
		$("#page_grid").html(_html);
	},
	showModeDetails : function(rowNum){
		var detailRowNum = parseInt($("#detailModeId"+rowNum).val())+1;
		var detailData = this.pageData[rowNum].orderDetailLst;
		var count = 0;
		var _html = '';
		var _dockStatus = true;
		for(i = detailRowNum; i < detailData.length; i++){
			if(++count > 3) break;
			if("40" != this.pageData[rowNum].orderDetailLst[i].dockStatus){
				_dockStatus = false;
			}
			_html +=''
				+'             <li '+(_dockStatus?'':'style="color:red;"')+'> '
				+'             <span class="dib" style="width: 40px;">&nbsp;</span> '
				+'             <span class="dib" style="width: 100px;">'+ this.getStr(detailData[i].sku)+'</span> '
				+'             <span class="dib" style="width: 260px;">'+ this.getStr(detailData[i].itemName)+'</span> '
				+'             <span class="dib" style="width: 90px;">'+ detailData[i].price+'</span> '
				+'             <span class="dib" style="width: 60px;">'+ detailData[i].qty+'</span> '
				+'             <span class="dib" style="width: 60px;">'+ detailData[i].currency+'</span> '
				+'             </li> ';
			$("#detailModeId"+rowNum).val(i);
		}
		$("#detailUL"+rowNum).append(_html);
	},
	tracking : function(){
		_this = this;
		webAlert({
            title:'查看',
            content:"未开通",
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"关闭",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	addView : function(rowNum){
		_this = this;
		webAlert({
            title:'查看',
            content:document.getElementById("address"+rowNum),
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"关闭",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	addModify : function(rowNum){
		_this = this;
		dictCtrl.dictionary.load("nation","nationHidden"+rowNum,"nation"+rowNum);
		webAlert({
            title:'修改',
            content:document.getElementById("addressModyfy"+rowNum),
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.doAddModify(rowNum);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	doAddModify : function(rowNum){
		_this = this;
		$.ajax({
		    url:_this.urlItems.addressModifyURL,
		    data:$('#addressForm'+rowNum).serialize(),  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	payOrder : function(id,orderNo){
		_this = this;
		webAlert({
            title:'提示',
            content:'确定支付订单:'+orderNo+'吗?',
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.doPayOrder(id);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	doPayOrder : function(id){
		_this = this;
		$.ajax({
		    url:_this.urlItems.payOrderURL,
		    data:{id:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		    	if(true == data.isSuccess){
		    		orderCtrl.order.queryPage();
		    	}
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	getStr : function(str){
		if(null == str
			|| "null" == str
				|| "NULL" == str){
			return "";
		}else{
			return str
		}
	},
	openCloseRow : function(rowNum){
		var status = $("#orderRowStatus"+rowNum).val();
		if("0" == status){
			$("#orderRowStatus"+rowNum).val("1");
			$("#orderRowDiv"+rowNum).show();
		}else{
			$("#orderRowStatus"+rowNum).val("0");
			$("#orderRowDiv"+rowNum).hide();
		}
	},
	delView : function(orderNo,id){
		_this = this;
		webAlert({
            title:'提示',
            content:'确定删除订单'+orderNo+' 吗?',
            opacity:.5,
            bg:"gray",
            width:300,
            height:10,
            button:[
                    {
                    name:"确定",
                    callback:function(){
                    	_this.delOrder(id);
                    	this.close();
                    }
                    },{
                    name:"取消",
                    callback:function(){
                  	  this.close();
                    }
                    }]
            });
	},
	delOrder : function(id){
		_this = this;
		$.ajax({
		    url:_this.urlItems.delOrderURL,
		    data:{id:id},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	window.webDialogUtil.alert("提示",data.msg);
		    	if(true == data.isSuccess){
		    		orderCtrl.order.queryPage();
		    	}
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	checkedAll : function(){
		var isChecked = $("#checkedAllBtn").is(':checked');
		var arrChk=$('input[name="chk_list"]');
		$(arrChk).each(function(){
			if(!this.disabled){
				this.checked=isChecked;
			}              
	    });
	},
	submitOrder : function(){
		var arrChk=$('input[name="chk_list"]');
		var ids = new Array();
	    $(arrChk).each(function(){
	    	if(this.checked){
	    		ids.push(parseInt(this.value));
	    	}                   
	    });
	    if(ids.length < 1){
	    	 window.webDialogUtil.alert("提示","请先勾选需要提交的订单");
	    	 return;
	    }
	    this.doSubmitOrder(ids);
	},
	doSubmitOrder : function(ids){
		if("number"==typeof(ids)){
			var tmp = new Array();
			tmp.push(parseInt(ids));
			ids = tmp;
		}
		_this = this;
		$.ajax({
		    url:_this.urlItems.submitOrderURL,
		    data:{ids:ids},  
		    type:'post',  
		    cache:false,  
		    dataType:'json',  
		    success:function(data) {
		    	if(data.isSuccess){
		    		window.webDialogUtil.alert("提示","订单提交成功");
		    		_this.queryPage();
		    	}else{
		    		window.webDialogUtil.alert("提示",data.msg);
		    	}
		     },  
		     error : function() {
		    	 window.webDialogUtil.alert("提示","操作失败");
		     }  
		});
	},
	uploadBatch:function(){
		var _this = this;
		$.ajaxFileUpload({
			url :_this.urlItems.uploadBatchURL,
			secureuri:false,
			fileElementId:'orderFile',//file标签的id
			dataType: 'json',
			success: function (data, status) {
				if(data.code!=10000){
					webDialogUtil.simpleAlert(data.msg, "温馨提示");
				}else{
					webDialogUtil.simpleAlert("导入成功", "温馨提示");
					_this.importView.close();
					_this.queryPage();
				}
			},
			error: function (data, status, e) {
				webDialogUtil.simpleAlert("处理异常", "温馨提示");
			}
		});
	},
	titleScroll : function(){
		$(document).scroll(function () {
	        if ($(document).scrollTop() > 300) {
	            $('.js_scroll').css({
	                "position":"fixed",
	                "top":"90px"
	            });
	        }else {
	            $('.js_scroll').css({
	                "position":"static",
	                "top":"0"
	            });
	        }
	    });
	},
	dataFormat : function(timeLong){
		if(null == timeLong
				|| "" == timeLong){
			return "";
		}
		return new Date(timeLong*1000).format("yyyy-MM-dd hh:mm:ss")
	},
	event : function(){
		_this = this;
		
		$("#searchButton").on("click",function(){
			_this.queryPage();
		});
		$("#submitOrderBtn").on("click",function(){
			_this.submitOrder();
		});
		$("#checkedAllBtn").on("click",function(){
			_this.checkedAll();
		});
		$('#js_daoru').click(function(){
            _this.importView=webAlert({
                title:'批量导入',
                content:document.getElementById("js_daoru_box"),
            });
        });
		$("#upload_btn").on("click",function(){
			if(!$("#orderFile").val()){
				webDialogUtil.simpleAlert("请选择文件", "温馨提示");
			}else{
				_this.uploadBatch();
			}
		});
		
		_this.queryPage();
		_this.titleScroll();
	},
};
$(function(){
	orderCtrl.order.event();
});